<template>
  <a-modal
    title="新增入库单"
    width="80%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          label="入库类型"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-select style="width: 100%" placeholder="请选择入库类型" v-decorator="['inType', {rules: [{ required: true, message: '请选择入库类型！' }]}]">
            <a-select-option v-for="(item,index) in inTypeData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="入库仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-tree-select
            v-decorator="[
              'warHouId',
              { rules: [{ required: true, message: '请选择入库仓库！' }] },
            ]"
            style="width: 100%"
            :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
            :treeData="wareHouseTree"
            placeholder="请选择入库仓库"
          >
            <span slot="title" slot-scope="{ id }">{{ id }} </span>
          </a-tree-select>
        </a-form-item>
        <a-form-item
          label="入库时间"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-date-picker
            style="width: 100%"
            :show-time="{ format: 'HH:mm' }"
            format="YYYY-MM-DD HH:mm"
            placeholder="请选择入库时间"
            v-decorator="['time',{rules: [{ required: true, message: '请选择入库时间！' }]}]"
            @change="timeOnChange"/>
        </a-form-item>
        <inv-in-table-form-item
          :dataSource="invDetailList"
          :proList="list.proList"
          :num="form.getFieldValue('num')?form.getFieldValue('num'):null"
          @add="({tableData})=>{ invDetailList = tableData}"
          @del="({tableData})=>{ invDetailList = tableData}"
        />
        <a-form-item
          label="备注信息"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-textarea placeholder="请输入备注信息" v-decorator="['remarks']" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
  import { invInAdd } from '@/api/modular/main/invIn/invInManage'
  import { proList } from '@/api/modular/main/pro/proManage'
  import { getWareHouseTree } from '@/api/modular/main/warehouse/wareHouseManage'
  import invInTableFormItem from '@/views/main/invIn/invInTableFormItem'
  import XEUtils from 'xe-utils'
  import moment from 'moment'
  export default {
    components: {
      invInTableFormItem
    },
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
          // 入库明细
        invDetailList: [],
        list: {
          // 产品
          proList: []
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        wareHouseTree: [],
        // 入库类型字典
        inTypeData: [],
        // 时间格式转化
        timeDateString: '',
        visible: false,
        confirmLoading: false,
        inLibraryTime: undefined,
        form: this.$form.createForm(this)
      }
    },
    methods: {
      moment,
      // 初始化方法
      async add (record) {
        this.time = new Date().toLocaleDateString()
        this.inLibraryTime = new Date()
        await proList().then(res => {
          this.list.proList = res.data
        })
        this.visible = true
        const data = await this.getWareHouseTree()
        const inTypeOption = this.$options
        this.inTypeData = inTypeOption.filters['dictData']('in_type')
        // 设置初始值
        setTimeout(() => {
          this.form.setFieldsValue({
            inType: this.inTypeData.length !== 0 ? this.inTypeData[0].code : '',
            warHouId: data.length !== 0 ? this.wareHouseTree[0].id : ''
          })
        }, 100)
        this.form.getFieldDecorator('time', { initialValue: moment(this.inLibraryTime, 'YYYY-MM-DD HH:mm:ss') })
        this.timeDateString = moment(this.inLibraryTime).format('YYYY-MM-DD HH:mm:ss')
        if (!record) {
          return
        }
        if (record.invDetailList && record.invDetailList.length > 0) {
          this.invDetailList = record.invDetailList.map(item => {
            item.id = undefined
            return item
          })
        }
        setTimeout(() => {
          this.form.setFieldsValue(
            {
              plaNum: record.plaNum,
              proModelId: record.proModelId,
              remarks: record.remarks
            }
          )
        }, 100)
      },
      getCurrentData() {
        return new Date().toLocaleDateString()
      },
      /**
       * 获取类型树，并加载于表单中
       */
      async getWareHouseTree() {
        var promise = getWareHouseTree().then((res) => {
          this.formLoading = false
          if (!res.success) {
            this.wareHouseTree = []
            return
          }
          this.wareHouseTree = res.data
        })
        await promise
        return this.wareHouseTree
      },
      /**
       * 提交表单
       */
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            values.code = XEUtils.trim(values.code)
            for (const key in values) {
              if (typeof (values[key]) === 'object' && values[key] != null) {
                values[key] = JSON.stringify(values[key])
              }
            }
            values.invDetailList = this.invDetailList || null
            values.invDetailList = Array.from(values.invDetailList, item => { return { proId: item.proId, num: item.num } })
            values.time = this.timeDateString || null
            invInAdd(values).then((res) => {
              if (res.success) {
                this.$message.success('新增成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error(res.message)// + res.message
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      timeOnChange(date, dateString) {
        this.timeDateString = dateString
        this.form.setFieldsValue({
          time: moment()
        })
      },

      handleCancel () {
        this.timeDateString = ''
        this.time = ''
        this.invDetailList = []
        this.form.getFieldDecorator('time', { initialValue: null })
        this.form.resetFields()
        this.visible = false
      }
    }
  }
</script>
